# coding=utf-8
"""
# Author : Hunter Oakley
# Time   : 2022/5/30 23:25
# Descripation: 项目中需要用的ModelForm类
"""
from django import forms
from web_user import models
from django.core.validators import RegexValidator
from django.core.validators import ValidationError
from utils.Bootstrap import BootStrapStyle
from utils.encrypt import md5

######## ModelForm类 #################
class MyForm(BootStrapStyle):

    # 需要对字段进行特殊的校验
    # name = forms.CharField(
    #     min_length=3,
    #     label="用户名",
    #     widget=forms.TextInput(attrs={"class": "form-control"})  # 也可以通过自定义校验时显示bootstrap属性
    # )

    class  Meta:
        # 关联models中定义的类
        model = models.UserInfo
        # 需要展示的字段
        fields = ["name","age","gender","password","depart","salary","create_time"]
        # 通过控制widgets插件来定制显示插件时内部的属性
        # widgets = {
        #     "name":forms.TextInput(attrs={"class":"form-control"}),
        #     "age":forms.TextInput(attrs={"class":"form-control"}),
        #     "gender":forms.TextInput(attrs={"class":"form-control"}),
        #     "password":forms.PasswordInput(attrs={"class":"form-control"}),
        #     "depart": forms.TextInput(attrs={"class": "form-control"}),
        #     "salary":forms.TextInput(attrs={"class":"form-control"}),
        #     "create_time":forms.TextInput(attrs={"class":"form-control"}),
        # }



class PrettyModel(BootStrapStyle):
    # 验证方式一
    # 单独对手机号进行验证
    mobile = forms.CharField(
        label="手机号",
        validators=[RegexValidator(r"^1[3-9]\d{9}$","手机号格式错误")], # 验证手机号正则表达式
    )

    class Meta:
        model = models.PrettyNum
        fields = ["mobile","price","level","status"]
        # fields = "__all__"
        # exclude = ["level"]

    # 验证方式二(利用钩子函数，函数名必须为clean_字段名)
    def clean_mobile(self):
        text_mobile = self.cleaned_data["mobile"] # 获取用户输入值，取其中的手机号

        # 根据获取的手机号，查询数据库中是否已存在，若存在则不能新建
        res = models.PrettyNum.objects.filter(mobile=text_mobile).exists()
        if res:
            raise ValidationError("手机号已存在")
        # if len(text_mobile) !=11:
        #     # 验证不通过
        #     raise ValidationError("手机号格式错误")
        # 验证通过,返回用户输入的值
        return text_mobile



class PrettyEditModel(BootStrapStyle):
    # 验证方式一
    # 单独对手机号进行验证
    mobile = forms.CharField(
        label="手机号",
        validators=[RegexValidator(r"^1[3-9]\d{9}$","手机号格式错误")], # 验证手机号正则表达式
    )

    # mobile = forms.CharField(
    #     label="手机号",
    #     disabled=True # 加上disabled属性可以让字段不可编辑
    # )

    class Meta:
        model = models.PrettyNum
        fields = ["mobile","price","level","status"]
        # fields = "__all__"  # 展示所有
        # exclude = ["level"]  # 除了level字段都展示出来

    #验证方式二(利用钩子函数，函数名必须为clean_字段名)
    def clean_mobile(self):
        text_mobile = self.cleaned_data["mobile"] # 获取用户输入值，取其中的手机号

        # 通过self.instance.pk获取当前编辑的哪一行(当前对象)的ID
        print(self.instance.pk)

        # 查看数据库中除了自己以外，其它数据中是否还存在手机号同样的情况,若存在，则手机号已存在不能提交
        res = models.PrettyNum.objects.filter(mobile=text_mobile).exclude(id=self.instance.pk).exists()
        if res:
            raise ValidationError("手机号已存在")
        # if len(text_mobile) !=11:
        #     # 验证不通过
        #     raise ValidationError("手机号格式错误")
        # 验证通过,返回用户输入的值
        return text_mobile


class AdminModleForm(BootStrapStyle):
    """
    admin的model
    """
    # 自定义一个确认密码的字段
    confirm_pwd = forms.CharField(
        label="确认密码",
        widget=forms.PasswordInput(render_value=True)  # 将插件改为密码输入框,让密码掩码显示
        # render_value为True时，密码不置空
    )

    class Meta:
        model = models.Admin
        fields = ["username","password","confirm_pwd"]
        widgets = {
            "password": forms.PasswordInput(render_value=True)  # 将插件改为密码输入框,让密码掩码显示
        }

    def clean_password(self):
        pwd = self.cleaned_data.get("password")
        return md5(pwd) # 加完密的pwd

    # 钩子函数去对比密码和确认密码是否一致
    def clean_confirm_pwd(self):
        # 获取提交的密码和确认密码
        # print(self.cleaned_data) # {'username': 'laocheng', 'password': '67fb6c25b5c783b0e80463190d0415ae', 'confirm_pwd': '123'}
        # password = self.cleaned_data["password"]
        password = self.cleaned_data.get("password")
        # confirm_pwd = md5(self.cleaned_data["confirm_pwd"])
        confirm_pwd = md5(self.cleaned_data.get("confirm_pwd"))
        if password!=confirm_pwd:
            raise ValidationError("密码不一致")

        # 钩子函数中renturn什么，保存到数据库中就是什么
        return confirm_pwd


class AdminEditModleForm(BootStrapStyle):
    """
    admin_edit的ModelForm
    """
    class Meta:
        model = models.Admin
        fields = ["username"]


class AdminResetModelForm(BootStrapStyle):
    """
    admin_reset的MmodelForm
    """
    confirm_pwd = forms.CharField(
        label="确认密码",
        widget=forms.PasswordInput(render_value=True)
    )

    class Meta:
        model = models.Admin
        fields = ["password","confirm_pwd"]
        widgets = {
            "password":forms.PasswordInput(render_value=True)
        }

    def clean_password(self):
        pwd = self.cleaned_data.get("password")
        md5_pwd= md5(pwd)

        # 获取当前输入的密码和数据库中的密码是否一致
        # 如果一致，不能进行修改
        # print(self.instance,type(self.instance))
        # print(self.instance.pk)
        exists = models.Admin.objects.filter(id=self.instance.pk,password=md5_pwd).exists() # 判断当前输入的密码和数据库中的密码是否一致
        # print(exists)
        if exists:
            raise ValidationError("不能跟之前的密码相同")
        return md5_pwd # 加完密的pwd

    # 钩子函数去对比密码和确认密码是否一致
    def clean_confirm_pwd(self):
        # 获取提交的密码和确认密码
        print(self.cleaned_data) # {'username': 'laocheng', 'password': '67fb6c25b5c783b0e80463190d0415ae', 'confirm_pwd': '123'}
        # password = self.cleaned_data["password"]
        password = self.cleaned_data.get("password") # get()方法获取password，如果没有返回None
        print(password)
        # confirm_pwd = md5(self.cleaned_data["confirm_pwd"])
        confirm_pwd = md5(self.cleaned_data.get("confirm_pwd"))
        if password!=confirm_pwd:
            raise ValidationError("密码不一致")

        # 钩子函数中renturn什么，保存到数据库中就是什么
        return confirm_pwd



class TaskModelForm(BootStrapStyle):
    """
    task的ModelForm
    """
    class Meta:
        model = models.Task
        fields = "__all__"
        widgets = {
            "detail":forms.TextInput
        }


class OrerModelForm(BootStrapStyle):
    """
    oder的ModelForm
    """
    class Meta:
        model = models.Order
        exclude = ["oid","admin"]  # 排除oid


class CityModelForm(BootStrapStyle):
    """
    文件上传的ModelForm
    """
    BootStrapStyle.exclude_fileds = ["img"]
    class Meta:
        model = models.City
        fields = "__all__"





